package at.fhj.itm10.ticketmaster.validators;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
/**
 * Validiert die E-Mail.
 * 
 * @author Sabrina Gruber
 */

@FacesValidator(value="ValidEMailValidator")
public class ValidEMailValidator implements Validator {

	public void validate(FacesContext facesContext, UIComponent uIComponent, Object object) {

		String enteredEmail = (String) object;

		// Set the email pattern string
		Pattern p = Pattern.compile("\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}\\b");

		// Match the given string with the pattern
		Matcher m = p.matcher(enteredEmail);

		// Check whether match is found
		boolean matchFound = m.matches();
		
		if (!matchFound) {
			String text = "Bitte geben Sie eine gültige E-Mail Adresse ein";
			
			FacesMessage message = new FacesMessage();
			message.setDetail(text);

			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(message);
		}

	}


}
